package com.zzzzzz.account.settings;

import java.io.IOException;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zzzzzz.account.signin.NoSuchOnlineUserException;
import com.zzzzzz.account.signin.OnlineService;
import com.zzzzzz.account.signin.UserPasswordException;
import com.zzzzzz.account.user.User;
import com.zzzzzz.account.user.UserBase;
import com.zzzzzz.account.user.UserDao;
import com.zzzzzz.common.message.Message;
import com.zzzzzz.common.message.MessageIcon;
import com.zzzzzz.core.web.BaseController;

@Controller
public class SettingsController extends BaseController {

	@Resource
	private UserDao userDao;
	@Resource
	private OnlineService onlineService;
	@Resource
	private SettingsService settingsService;

	@RequestMapping(value="/account/settings/profile", method=RequestMethod.GET)
	public String editProfilePage(Model model, @ModelAttribute EditProfileForm editProfileForm) throws NoSuchOnlineUserException {
		model.addAttribute("tab", "profile");
		
		User user = onlineService.findUser();
		editProfileForm.setUsername(user.getUsername());
		editProfileForm.setAboutMe(user.getAboutMe());
		editProfileForm.setWebsite(user.getWebsite());
		return "account/settings/editProfile";
	}
	
	
	@RequestMapping(value="/account/settings/profile", method=RequestMethod.POST)
	public String processEditProfile(Model model, @Valid EditProfileForm editProfileForm, BindingResult bindingResult, RedirectAttributes redirectAttributes, Locale locale) throws NoSuchOnlineUserException {
		if(bindingResult.hasErrors()) {
			return editProfilePage(model, editProfileForm);
		}
		
		Long userId = onlineService.findUserId();
		userDao.editProfile(userId, editProfileForm.getUsername(), editProfileForm.getWebsite(), editProfileForm.getAboutMe());
		
//		updateCurrentUsername(editProfileForm.getUsername());
		
		redirectAttributes.addFlashAttribute(Message.success(MessageIcon.OK + getMessage("message.success.form.edit.submit", locale)));
		return "redirect:/account/settings/profile";
	}
	
	@RequestMapping(value="/account/settings/portrait", method=RequestMethod.GET)
	public String editPortraitPage(Model model, @ModelAttribute EditPortraitForm editPortraitForm) throws NoSuchOnlineUserException {
		model.addAttribute("tab", "portrait");
		return "account/settings/editPortrait";
	}
	
	@RequestMapping(value="/account/settings/portrait", method=RequestMethod.POST)
	public String editPortrait(Model model, @Valid EditPortraitForm editPortraitForm, BindingResult bindingResult, RedirectAttributes redirectAttributes, Locale locale) throws NoSuchOnlineUserException {
		if(bindingResult.hasErrors()) {
			return editPortraitPage(model, editPortraitForm);
		}
		try {
			settingsService.editPortrait(editPortraitForm);
			redirectAttributes.addFlashAttribute(Message.success(MessageIcon.OK + getMessage("message.success.form.edit.submit", locale)));
		} catch (MaxUploadSizeExceededException e) {
			logger.debug("/account/settings/portrait", e);
			redirectAttributes.addFlashAttribute(Message.error(MessageIcon.WARNING + getMessage("message.error.form.account.settings.portrait.upload", locale)));
		} catch (IOException e) {
			logger.warn("/account/settings/portrait", e);
			redirectAttributes.addFlashAttribute(Message.error(MessageIcon.WARNING + getMessage("message.error.form.upload.submit", locale)));
		}
		return "redirect:/account/settings/portrait";
	}
	
	@RequestMapping(value="/account/settings/password", method=RequestMethod.GET)
	public String editPasswordPage(Model model, @ModelAttribute EditPasswordForm editPasswordForm) {
		model.addAttribute("tab", "password");
		return "account/settings/editPassword";
	}
	
	@RequestMapping(value="/account/settings/password", method=RequestMethod.POST)
	public String editPassword(Model model, @Valid EditPasswordForm editPasswordForm, BindingResult bindingResult, RedirectAttributes redirectAttributes, Locale locale) throws Exception {
		if(bindingResult.hasErrors()) {
			return editPasswordPage(model, editPasswordForm);
		}
		try{
			settingsService.editPassword(editPasswordForm.getCurPassword(), editPasswordForm.getNewPassword());
			redirectAttributes.addFlashAttribute(Message.success(MessageIcon.OK + getMessage("message.success.form.edit.submit", locale)));
			return "redirect:/account/settings/password";
		}catch(UserPasswordException userPasswordException) {
			bindingResult.rejectValue("curPassword", "message.error.password.wrong");
			return editPasswordPage(model, editPasswordForm);
		}
	}
	
	/**
	 * 更新Shiro中当前用户的用户名.
	 */
	private void updateCurrentUsername(String username) {
		UserBase userBase = (UserBase) SecurityUtils.getSubject().getPrincipal();
		userBase.setUsername(username);
	}
	
	/*@RequestMapping(value="/account/settings/email", method=RequestMethod.GET)
	public String editEmailPage(Model model, @ModelAttribute EditEmailForm editEmailForm) throws NoSuchOnlineUserException {
		model.addAttribute("tab", "email");
		User user = onlineService.findUser();
		editEmailForm.setEmail(user.getEmail());
		return "account/settings/editEmail";
	}
	
	@RequestMapping(value="/account/settings/email", method=RequestMethod.POST)
	public String editEmail(Model model, @Valid EditEmailForm editEmailForm, BindingResult bindingResult, RedirectAttributes redirectAttributes, Locale locale) throws NoSuchOnlineUserException {
		if(bindingResult.hasErrors()) {
			return editEmailPage(model, editEmailForm);
		}
		try {
			settingsService.editEmail(editEmailForm.getPassword(), editEmailForm.getEmail());
			redirectAttributes.addFlashAttribute(Message.success(getMessage("message.success.form.edit.submit", locale), MessageIcon.OK));
			return "redirect:/account/settings/email";
		} catch (UserPasswordException e) {
			bindingResult.rejectValue("password", "message.error.password.wrong");
			return editEmailPage(model, editEmailForm);
		}
		
	}*/
	
	private static final Logger logger = LoggerFactory.getLogger(SettingsController.class);
	
}
